package com.tc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tc.dao.AddressMapper;
import com.tc.dao.OrderItemMapper;
import com.tc.dao.OrderMapper;
import com.tc.dao.TrucksMapper;
import com.tc.pojo.*;
import com.tc.service.OrderService;
import com.tc.controller.WebSocketServer;
import com.tc.vo.OrderAndAddress;
import entity.Result;
import entity.StatusCode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;

/****
 * @Author:admin
 * @Description:Order业务层接口实现类
 * @Date 2019/6/14 0:16
 *****/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private TrucksMapper trucksMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * Order条件+分页查询
     * @param order 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<Order> findPage(Order order, int page, int size){
        //分页
        PageHelper.startPage(page,size);
        //搜索条件构建
        Example example = createExample(order);
        //执行搜索
        return new PageInfo<Order>(orderMapper.selectByExample(example));
    }

    /**
     * Order分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Order> findPage(int page, int size){
        //静态分页
        PageHelper.startPage(page,size);
        //分页查询
        return new PageInfo<Order>(orderMapper.selectAll());
    }

    /**
     * Order条件查询
     * @param order
     * @return
     */
    @Override
    public List<Order> findList(Order order){
        //构建查询条件
        Example example = createExample(order);
        //根据构建的条件查询数据
        return orderMapper.selectByExample(example);
    }


    /**
     * Order构建查询对象
     * @param order
     * @return
     */
    public Example createExample(Order order){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(order!=null){
            // 订单id
            if(!StringUtils.isEmpty(order.getId())){
                    criteria.andEqualTo("id",order.getId());
            }
            // 用户的id
            if(!StringUtils.isEmpty(order.getUid())){
                    criteria.andEqualTo("uid",order.getUid());
            }
            // 司机的id
            if(!StringUtils.isEmpty(order.getDid())){
                    criteria.andEqualTo("did",order.getDid());
            }
            // 汽车的id号
            if(!StringUtils.isEmpty(order.getTid())){
                    criteria.andEqualTo("tid",order.getTid());
            }
            // 订单编号
            if(!StringUtils.isEmpty(order.getOrderSn())){
                    criteria.andEqualTo("orderSn",order.getOrderSn());
            }
            // 提交时间
            if(!StringUtils.isEmpty(order.getCreateTime())){
                    criteria.andEqualTo("createTime",order.getCreateTime());
            }
            // 订单状态：0->待付款；1->待接单；2->已接单；3->已完成；4->已关闭；5->无效订单
            if(!StringUtils.isEmpty(order.getStatus())){
                    criteria.andEqualTo("status",order.getStatus());
            }
            // 订单总金额
            if(!StringUtils.isEmpty(order.getTotalAmount())){
                    criteria.andEqualTo("totalAmount",order.getTotalAmount());
            }
            // 应付金额（实际支付金额）有优惠券功能考虑
            if(!StringUtils.isEmpty(order.getPayAmount())){
                    criteria.andEqualTo("payAmount",order.getPayAmount());
            }
            // 支付方式：0->未支付；1->支付宝；2->微信
            if(!StringUtils.isEmpty(order.getPayType())){
                    criteria.andEqualTo("payType",order.getPayType());
            }
            // 运输公司的id
            if(!StringUtils.isEmpty(order.getCid())){
                    criteria.andEqualTo("cid",order.getCid());
            }
        }
        return example;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Long id){
        orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改Order
     * @param order
     */
    @Override
    public void update(Order order){
        orderMapper.updateByPrimaryKey(order);
    }

    /**
     * @param order
     * 增加Order
     */
    @Override
    public Result add(Order order, Address address){
        order.setCreateTime(new Date());
        String orderNo = UUID.randomUUID().toString();
        order.setOrderSn(orderNo);
        order.setStatus(1);
        order.setPayType(0);
        //以下算出这个客户运算距离加运算位置后的总付值

//        Stringm orderNo2 = UUID.randomUUID().toString();
        Map data = new HashMap();
        //订单号
        data.put("order",order);
        data.put("address",address);
        try{
        rabbitTemplate.convertAndSend("orderwait-exchange","orderwait."+orderNo,data);
            return new Result(true,StatusCode.OK,"订单生成成功",order.getOrderSn());
        }catch (Exception e){
            e.printStackTrace();
            return new Result(true, StatusCode.ERROR,"订单请求失败");
        }

    }

    /***
    * 求金额
     * @param map
     */
    @Override
    public Result Howmoney(Map map){
        //以下算出这个客户运算距离加运算位置后的总付值
        Integer price2= (Integer) map.get("price");
        double price;
        long uid= (int)map.get("uid");
        long tid= (int)map.get("tid");
        long distance=Long.parseLong((String) map.get("distance"));
        distance=distance/1000;
        //基于货车id 查询货车相关信息 金额
        Trucks trucks=new Trucks();
        trucks.setId((int) tid);
        Trucks trucksOK=trucksMapper.selectByPrimaryKey(trucks);
        //获取金额后进行计算 距离判断大小
        if(distance>0){
            //所有起步价有五公里起步
            long i = distance-5;
            price=price2+i*trucksOK.getPricekm();
            if(distance>35){
                price-=(distance-35)*trucksOK.getPricekm()*0.3;
            }
            BigDecimal b = new BigDecimal(price);
            return new Result(true, StatusCode.OK,"计算结果成功", b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        }else{
            return new Result(false, StatusCode.ERROR,"计算结果失败",null);
        }
        //查询客户是否有vip 进行打折计算(暂时不做)
    }

    /**
     * 根据ID查询Order
     * @param id
     * @return
     */
    @Override
    public Order findById(Long id){
        return  orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询Order全部数据
     * @return
     */
    @Override
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    @Override
    public Result DriverFindOrder() {
        List<OrderAndAddress> redisOrders=null;
       if (redisTemplate.opsForHash().entries("orderwait").size()>=1){
           redisOrders= redisTemplate.opsForHash().values("orderwait");
           return new Result<Order>(true, StatusCode.OK, "刷新成功",redisOrders);
        }else {
           return new Result<Order>(true, StatusCode.ERROR, "当前没有订单");
       }
    }
    @Transactional
    @Override
    public Result DriverDoOrder(OrderAndAddress doOrder) {
       Order order= doOrder.getOrder();
       Address address= doOrder.getAddress();
       DriverAddress driverAddress= doOrder.getDriverAddress();
       //订单的存储
       order.setDid(Long.valueOf(driverAddress.getId()));
       try {
           orderMapper.insert(order);
           //地址的存储
           address.setOrderSn(order.getOrderSn());
           address.setDidxy(address.getDidxy());
           addressMapper.insert(address);
//       //详细订单存储
//       OrderItem orderItem=new OrderItem();
//       orderItem.setOrderSn(order.getOrderSn());
//       orderItem.setCreateTime(order.getCreateTime());
//       orderItem.setTotalAmount(order.getTotalAmount());
//
//       orderItemMapper.insert(orderItem);
           redisTemplate.opsForHash().delete("orderwait",order.getOrderSn());
           WebSocketServer.sendInfo(new Result(true, StatusCode.OK, "接单成功订单编号"+order.getOrderSn()),"5");
           return new Result(true, StatusCode.OK, "接单成功订单编号"+order.getOrderSn());
       }catch (Exception e){
           e.printStackTrace();
           return new Result(true, StatusCode.ERROR, "接单异常");
       }

    }
}
